'use strict'
/**
 * 用户登录注册相关控制器
 */
const userModel = require("../models/user");
const uuid = require("uuid");
const md5 = require("../utils/index").md5;
const jwt = require('jwt-simple'); //创建token
const config = require("config-lite")(__dirname);
/**
 * 注册用户
 * @param {*} ctx 
 * @param {*} next 
 */
exports.register = async (ctx,next) => {
    const body = ctx.request.body;//获取参数
	const params = {
        uuid : uuid.v1(),
		name : body.name,
		password : md5(body.password),//md5加密
		email : body.email,
		username : body.username
	}
	var register = await userModel.save(params);
	if(register){
		ctx.body =  {
			code:"0",
			message: 'success',
		}
	}else{
		ctx.body ={
			code:"-1",
			message: 'error',
		}
    }
    return next;
}
/**
 * 
 * @param {*} ctx 
 * @param {*} next 
 */
exports.login = async (ctx,next) => {
    const body = ctx.request.body;
    var params = {
        username : body.username,
        password : md5(body.password)
    }
    var data = await userModel.login(params);
    if(data.length > 0){
        const token = jwt.encode({uuid : data[0].uuid,iat : new Date().getTime(),exp: new Date().getTime() + 86400000}, config.secret)  //token签名 有效期为1小时
		ctx.body =  {
			code:"0",
            message: 'success',
            content :{
                uuid     : data[0].uuid,
                username : data[0].username,
                name     : data[0].name,
				email    : data[0].email,
				headUrl  : data[0].headUrl,
                token    : token
            } 
		}
	}else{
		ctx.body ={
			code:"-1",
			message: '用户名或者密码不正确',
		}
    }
    return next;
}